# Generated manually for foreign key migration

from django.db import migrations, models
import django.db.models.deletion


def update_session_user_references(apps, schema_editor):
    """
    更新ConversationSession的user引用
    将user_id从指向APIKey改为指向User
    处理重复的session_id问题
    """
    db_alias = schema_editor.connection.alias
    APIKey = apps.get_model('deepseek_api', 'APIKey')
    User = apps.get_model('deepseek_api', 'User')
    ConversationSession = apps.get_model('deepseek_api', 'ConversationSession')
    
    # 为每个会话找到对应的User
    sessions = ConversationSession.objects.using(db_alias).all()
    updated_count = 0
    deleted_count = 0
    merged_count = 0
    
    session_count = sessions.count()
    print(f"\n正在更新 {session_count} 条会话记录...")
    
    if session_count == 0:
        print("没有会话需要更新\n")
        return
    
    # 按session_id分组处理，避免唯一约束冲突
    session_groups = {}
    for session in sessions:
        session_id = session.session_id
        if session_id not in session_groups:
            session_groups[session_id] = []
        session_groups[session_id].append(session)
    
    print(f"发现 {len(session_groups)} 个不同的session_id")
    
    for session_id, session_list in session_groups.items():
        try:
            # 获取第一个会话的APIKey
            first_session = session_list[0]
            api_key = APIKey.objects.using(db_alias).get(id=first_session.user_id)
            user = User.objects.using(db_alias).get(username=api_key.user[:100])
            
            if len(session_list) == 1:
                # 只有一个会话，直接更新
                ConversationSession.objects.using(db_alias).filter(id=first_session.id).update(user_id=user.id)
                updated_count += 1
            else:
                # 多个会话有相同的session_id，需要合并
                print(f"  - 合并session_id '{session_id}' 的 {len(session_list)} 个会话")
                
                # 合并所有会话的context
                merged_context = ""
                for session in session_list:
                    if session.context:
                        merged_context += session.context + "\n"
                
                # 删除所有旧会话
                for session in session_list:
                    ConversationSession.objects.using(db_alias).filter(id=session.id).delete()
                    deleted_count += 1
                
                # 创建一个新的合并会话
                ConversationSession.objects.using(db_alias).create(
                    session_id=session_id,
                    user=user,
                    context=merged_context.strip()
                )
                merged_count += 1
                
        except APIKey.DoesNotExist:
            print(f"  - ⚠️ APIKey不存在，删除session_id '{session_id}' 的所有会话")
            for session in session_list:
                ConversationSession.objects.using(db_alias).filter(id=session.id).delete()
                deleted_count += 1
        except User.DoesNotExist:
            print(f"  - ⚠️ 找不到对应User，删除session_id '{session_id}' 的所有会话")
            for session in session_list:
                ConversationSession.objects.using(db_alias).filter(id=session.id).delete()
                deleted_count += 1
    
    print(f"✅ 成功更新 {updated_count} 条会话")
    print(f"✅ 合并了 {merged_count} 个重复会话")
    if deleted_count > 0:
        print(f"⚠️  删除了 {deleted_count} 条无效会话\n")


class Migration(migrations.Migration):

    dependencies = [
        ('deepseek_api', '0002_user_migrate_data'),
    ]

    operations = [
        # 先更新数据
        migrations.RunPython(update_session_user_references, migrations.RunPython.noop),
        # 再更改外键
        migrations.AlterField(
            model_name='conversationsession',
            name='user',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sessions', to='deepseek_api.user'),
        ),
    ]

